package model

import (
	"common-admin/entity"
)

type Menu struct {
	Id       int
	Title    string
	Uri      string
	Pid      int
	Sort     int
	Group    string
	Spread   bool
	Children []*Menu
}

func (o *Menu) FindById(id int) entity.Menu {
	db := Model().getDb()
	var Menu entity.Menu
	db.First(&Menu, id)
	defer Model().Close()
	return Menu
}

func (o *Menu) FindOne(Menu *entity.Menu) {
	db := Model().getDb()
	db.Where(Menu).First(&Menu)
	defer Model().Close()
}

func (o *Menu) FindByUsername(username string) entity.Menu {
	db := Model().getDb()
	var Menu entity.Menu
	// 设置为true之后控制台会输出对应的SQL语句
	db.LogMode(true)
	db.Where("username = ?", username).First(&Menu)
	defer Model().Close()
	return Menu
}

func (o *Menu) FindAll() []entity.Menu {
	db := Model().getDb()
	Menu := make([]entity.Menu, 0)
	db.Find(&Menu)
	defer Model().Close()
	return Menu
}

func (o *Menu) GetMenus(roleId int) []entity.Menu {
	db := Model().getDb()
	menus := make([]entity.Menu, 0)
	if roleId > 1 {
		db = db.Where("id in (?)", []int{1, 2, 3})
	}
	db.Find(&menus)
	return menus
}

func (o *Menu) MenuTree(menus []entity.Menu, pid int) []*Menu {
	menuData := []*Menu{}
	for _, v := range menus {
		menu := &Menu{}
		menu.Spread = false
		menu.Id = v.Id
		menu.Title = v.Title
		menu.Uri = v.Uri
		menu.Group = v.Group
		menu.Pid = v.Pid
		if v.Pid == pid {
			child := o.MenuTree(menus, v.Id)
			menu.Children = child
			menuData = append(menuData, menu)
		}
	}
	return menuData
}

func (o *Menu) MenuTree2(menus []entity.Menu, pid int) map[int]interface{} {
	menuData := make(map[int]interface{})
	for k, v := range menus {
		data := make(map[string]interface{})
		data["id"] = v.Id
		data["title"] = v.Title
		data["uri"] = v.Uri
		data["group"] = v.Group
		data["pid"] = v.Pid
		data["spread"] = false
		if v.Pid == pid {
			data["children"] = o.MenuTree2(menus, v.Id)
			if data["children"] == nil {
				delete(data, "children")
			}
			menuData[k] = data
		}
	}
	return menuData
}

/**
菜单列表
*/
func (o *Menu) MenuList() []*Menu {
	return o.getMenu(0)
}

/**
递归获取树形菜单
*/
func (o *Menu) getMenu(pid int) []*Menu {
	var menu []Menu
	db := Model().getDb()
	db.Where("pid = ?", pid).Order("sort").Find(&menu)
	defer Model().Close()
	treeList := []*Menu{}
	for _, v := range menu {
		child := v.getMenu(v.Id)
		node := &Menu{
			Id:     v.Id,
			Title:  v.Title,
			Sort:   v.Sort,
			Uri:    v.Uri,
			Pid:    v.Pid,
			Spread: false,
		}
		node.Children = child
		treeList = append(treeList, node)
	}
	return treeList
}
